
#ifndef __timer_c__
#define __timer_c__

#include <zneo.h>

#include "timer.h"

#define TIMER0_PRESCALAR  128
#define T0_RELOAD_VALUE   ( SYS_CLK_FREQ / (TIMER0_DELAY * TIMER0_PRESCALAR ))

#define CLOCK_UNLOCK_STEP1 0xE7
#define CLOCK_UNLOCK_STEP2 0x18


// Shamelessly stolen from the ZiLOG Samples
void InitSystemClock(void) {
	unsigned char temp_image;

#if ( SYS_CLK_FREQ == EXTERNAL_CLK_FREQ )	
	unsigned int clock_delay;

	if( (OSCCTL & 0x42) != 0x42 )
	{
		temp_image = OSCCTL;								
		OSCCTL = CLOCK_UNLOCK_STEP1;		
		OSCCTL = CLOCK_UNLOCK_STEP2;
		OSCCTL = 0xC0;			

		clock_delay = 2000;
		while (clock_delay--);

		temp_image &= 0x3C;									
		temp_image |= 0x42;

		OSCCTL = CLOCK_UNLOCK_STEP1;		
		OSCCTL = CLOCK_UNLOCK_STEP2;		
		OSCCTL = temp_image;	
	}
#else
	if( (OSCCTL & 0x87) != 0x80 )		
	{
		temp_image = OSCCTL;
		temp_image &= 0x3C;
		temp_image |= 0x80;
		OSCCTL = CLOCK_UNLOCK_STEP1;	
		OSCCTL = CLOCK_UNLOCK_STEP2;	
		OSCCTL = temp_image;
	}	
#endif
}

void InitTimer(void) {
	T0CTL1 &= 0x80;

	T0CTL1 |= 0x79;
	T0HL    = 0x0001;   
	T0R     = T0_RELOAD_VALUE;      

	IRQ0ENH |= 0x20;
	IRQ0ENL |= 0x20;
}

static unsigned int s_CurrentMilliseconds;

#pragma interrupt
void isr_timer0( void )
{ 
	SET_VECTOR(TIMER0, isr_timer0);
	++s_CurrentMilliseconds;
}

void ResetTime(void) {
	s_CurrentMilliseconds = 0;
}

void StartTimer(void) {
	T0CTL1 |= ENABLE_TIMER;
	EI();
}

void StopTimer(void) {
	T0CTL1 &= DISABLE_TIMER;
}

unsigned int GetTime(void) {
	return (s_CurrentMilliseconds / 10);
}

void DelayMilliseconds( unsigned int msToDelay )
{
	s_CurrentMilliseconds = 0;
	T0CTL1 |= ENABLE_TIMER;
	EI();
	while(s_CurrentMilliseconds < msToDelay);
	T0CTL1 &= DISABLE_TIMER;
}

#endif